/*
 * @Author: Qimu
 * @Date: 2020-04-20 02:15:31
 * @LastEditors: Qimu
 * @LastEditTime: 2020-07-09 19:43:43
 * @Description: file content
 * @FilePath: \vue-admin-koa2\koa2_api\module\utlis\query.js
 */

/* 
   Model.deleteMany()
   Model.deleteOne()
   Model.find()
   Model.findById()
   Model.findByIdAndDelete()
   Model.findByIdAndRemove()
   Model.findByIdAndUpdate()
   Model.findOne()
   Model.findOneAndDelete()
   Model.findOneAndRemove()
   Model.findOneAndUpdate()
   Model.replaceOne()
   Model.updateMany()
   Model.updateOne()
*/

const query = {
  //查询数据
  find(model, obj) {
    return new Promise((resolve, reject) => {
      model.find(obj, (err, res) => {
        err ? reject(err) : resolve(res)
      })
    })
  },

  //保存数据
  save(model, obj1) {
    return new Promise((resolve, reject) => {
      new model(obj1).save((err, res) => {
        err ? reject(err) : resolve(res)
      })
    })
  },

  //修改数据
  updateOne(model, obj1, obj2) {
    return new Promise((resolve, reject) => {
      model.updateOne(obj1, obj2, (err, res) => {
        err ? reject(err) : resolve(res)
      })
    })
  },

  //删除数据
  deleteOne(model, obj) {
    return new Promise((resolve, reject) => {
      model.deleteOne(obj, (err, res) => {
        err ? reject(err) : resolve(res)
      })
    })
  },

  //查找ID 删除
  findByIdAndDelete(model, id) {
    return new Promise((resolve, reject) => {
      model.findByIdAndDelete(id, (err, res) => {
        err ? reject(err) : resolve(res)
      })
    })
  },

  //查找ID 数据
  findById(model, id) {
    return new Promise((resolve, reject) => {
      model.findById(id, (err, res) => {
        err ? reject(err) : resolve(res)
      })
    })
  },

  //查询列表总数 忽略查询条件，返回所有数据的数目长度
  count(model) {
    return new Promise((resolve, reject) => {
      model.estimatedDocumentCount((err, res) => {
        err ? reject(err) : resolve(res)
      })
    })
  },

  //countDocuments()：符合查询条件的数目长度
  countDocuments(model, obj) {
    return new Promise((resolve, reject) => {
      model.countDocuments(obj, (err, res) => {
        err ? reject(err) : resolve(res)
      })
    })
  },

  //聚合查询
  aggregate(model, options) {
    return new Promise((resolve, reject) => {
      model.aggregate(options, (err, res) => {
        err ? reject(err) : resolve(res)
      })
    })
  },
}

exports = module.exports = query;